﻿using System;
using System.Collections.Generic;
using System.Text;

namespace USERS.CYT369.COM.UTILITY
{
    public class UserAgentService
    {
        public static Browser Parse(string userAgent)
        {
            if (!string.IsNullOrEmpty(userAgent))
            {
                var browser = new Browser();
                int userAgentLength = userAgent.Length;

                var start = 0;
                var end = 0;
                var isBracket = false;

                for (end = 0; end < userAgentLength; end++)
                {
                    switch (userAgent[end])
                    {
                        case ' ':
                            if (!isBracket)
                            {
                                start = ParseSubStr(browser, userAgent, start, end);
                            }
                            break;

                        case '(':
                            isBracket = true;
                            break;

                        case ')':
                            isBracket = false;
                            break;

                        default:
                            break;
                    }
                }
                if (end > start)
                {
                    start = ParseSubStr(browser, userAgent, start, end);
                }



                return browser;
            }

            return null;
        }

        private static int ParseSubStr(Browser browser, string userAgent, int start, int end)
        {
            var str = userAgent.Substring(start, end - start);

            if (str[0] == '(')
            {
                var sps = str.Substring(1, str.Length - 2).Split(new char[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries);
                var brackets = new Dictionary<string, string>();
                foreach (var s in sps)
                {
                    ParseKeyValue(brackets, s);
                }
                browser.Brackets.Add(brackets);
            }
            else
            {
                ParseKeyValue(browser, str);
            }

            return end + 1;
        }

        private static void ParseKeyValue(Browser browser, string str)
        {
            var slashIndex = str.IndexOf('/');
            if (slashIndex > 0)
            {
                var k = str.Substring(0, slashIndex);
                var v = str.Substring(slashIndex + 1, str.Length - slashIndex - 1);
                browser.Add(k, v);
            }
            else
            {
                browser.Add(str, string.Empty);
            }
        }

        private static void ParseKeyValue(Dictionary<string, string> brackets, string str)
        {
            if (str != null) { str = str.Trim(); }
            var slashIndex = str.IndexOf('/');
            if (slashIndex > 0)
            {
                var k = str.Substring(0, slashIndex);
                var v = str.Substring(slashIndex + 1, str.Length - slashIndex - 1);
                brackets.Add(k, v);
            }
            else
            {
                brackets.Add(str, string.Empty);
            }
        }

    }

    public class Browser : Dictionary<string, string>
    {
        public List<Dictionary<string, string>> Brackets { get; set; } = new List<Dictionary<string, string>>();

        public BrowserInfo BrowserInfo
        {
            get
            {
                #region Browser Check
                if (this.ContainsKey("Edg"))
                {
                    return new BrowserInfo("Edg", this["Edg"]);
                }

                if (this.ContainsKey("VivoBrowser"))
                {
                    return new BrowserInfo("VivoBrowser", this["VivoBrowser"]);
                }

                if (this.ContainsKey("MicroMessenger"))
                {
                    return new BrowserInfo("MicroMessenger", this["MicroMessenger"]);
                }

                if (this.ContainsKey("Chrome"))
                {
                    return new BrowserInfo("Chrome", this["Chrome"]);
                }

                if (this.ContainsKey("Safari"))
                {
                    return new BrowserInfo("Safari", this["Safari"]);
                }
                #endregion

                #region IE11
                if (this.Brackets.Count > 0)
                {
                    foreach (var item in this.Brackets[0])
                    {
                        if (item.Key.Contains("rv"))
                        {
                            var sps = item.Value.Split(':');
                            if (sps.Length >= 2)
                            {
                                if (sps[0] == "rv")
                                {
                                    return new BrowserInfo("IE", sps[1]);
                                }
                            }
                        }
                    }
                }
                #endregion


                return null;
            }
        }

        public Platform Platform
        {
            get
            {
                var platform = new Platform();
                if (this.ContainsKey("Mobile")) { platform.IsMobile = true; }

                if (this.Brackets.Count > 0)
                {
                    int index = 0;
                    foreach (var item in this.Brackets[0])
                    {
                        switch (index)
                        {
                            case 0:
                                platform.OperatingSystem = item.Key;
                                index++;
                                break;

                            case 1:
                                platform.Model = item.Key;
                                index++;
                                break;

                            case 2:
                                platform.Manufacturer = item.Key;
                                index++;
                                break;
                        }
                    }
                }

                return platform;
            }
        }



        public override string ToString()
        {
            var sb = new System.Text.StringBuilder();
            foreach (var item in this)
            {
                if (string.IsNullOrEmpty(item.Value))
                {
                    sb.AppendLine(item.Key);
                }
                else
                {
                    sb.AppendLine($"{item.Key}/{item.Value}");
                }
            }

            foreach (var bracket in this.Brackets)
            {
                sb.Append("(");

                foreach (var item in bracket)
                {
                    if (string.IsNullOrEmpty(item.Value))
                    {
                        sb.Append(item.Key + "; ");
                    }
                    else
                    {
                        sb.Append($"{item.Key}/{item.Value}; ");
                    }
                }
                sb.Append(")\r\n");
            }

            return sb.ToString();
        }
    }

    public class BrowserInfo
    {
        public BrowserInfo(string name, string version)
        {
            this.Name = name;
            this.Version = version;
        }
        public string Name { get; set; }
        public string Version { get; set; }
    }

    public class Platform
    {
        public bool IsMobile { get; set; }

        /// <summary>
        /// 操作系统
        /// </summary>
        public string OperatingSystem { get; set; }

        /// <summary>
        /// 系统版本
        /// </summary>
        public string Model { get; set; }

        /// <summary>
        /// 生产厂家
        /// </summary>
        public string Manufacturer { get; set; }
    }


}
